<template>
  <j-modal
    :state='state'
    :width='1200'
    :visible='visible'
    :title='title'
    switchFullscreen
    @ok='handleSubmit'
    @cancel='close'
    style='top:50px;'
    cancelText='关闭'
  >
    <a-tabs :active-key='activeKey' @tabClick='tabClick'>
      <a-tab-pane v-if='state' key='role' tab='关联职位'>
        <a-spin tip='Loading...' :spinning='false'>
          <a-row :gutter='10' style='padding: 10px; margin: -10px' v-if='visible'>
            <a-col :md='12' :sm='24'>
              <a-card :bordered='false'>
                <a-form layout='inline' @keyup.enter.native='searchQuery'>
                  <a-row :gutter='24'>
                    <a-col :md='7' :sm='24'>
                      <a-form-item label=''>
                        <a-input placeholder='门店编号' v-model='queryParam.customerCode'></a-input>
                      </a-form-item>
                    </a-col>
                    <a-col :md='7' :sm='24'>
                      <a-form-item label=''>
                        <a-input placeholder='门店名称' v-model='queryParam.customerName'></a-input>
                      </a-form-item>
                    </a-col>
                    <a-col :md='7' :sm='24'>
                      <a-button type='primary' @click='searchQuery' icon='search' style='margin-top: 5px'>查询</a-button>
                    </a-col>
                  </a-row>
                </a-form>
                <a-table
                  ref='table'
                  size='middle'
                  bordered
                  :scroll="{
                    x:'max-content'
                  }"
                  tableLayout='auto'
                  rowKey='customerCode'
                  :columns='customersColumns'
                  :dataSource='customers'
                  :pagination='ipagination'
                  :loading='loading'
                  :rowSelection='{selectedRowKeys: customerSelectedRowKeys,
                   onSelect: onSelect,onSelectAll:onSelectAll}'
                  @change='handleTableChange'
                >

                  <template slot='mainPosition' slot-scope='text, record, index' v-if='false'>
                    {{ text }}
                  </template>
                  <template slot='imgUrl' slot-scope='text, record, index'>
                    <div class='anty-img-wrap'>
                      <a-avatar shape='square' :src='record.imgUrl' icon='user' />
                    </div>
                  </template>
                  <template slot='status' slot-scope='text'>{{ text | isActiveStatus }}</template>
                </a-table>

              </a-card>
            </a-col>
            <a-col :md='12' :sm='24'>
              <a-card :bordered='false'>
                <a-table
                  ref='table'
                  size='middle'
                  bordered
                  :scroll="{
                    x:'max-content'
                  }"
                  tableLayout='auto'
                  rowKey='customerCode'
                  :columns='customersColumns'
                  :dataSource='customersData'
                >
                  <template slot='imgUrl' slot-scope='text, record, index'>
                    <div class='anty-img-wrap'>
                      <a-avatar shape='square' :src='record.imgUrl' icon='user' />
                    </div>
                  </template>
                  <template slot='status' slot-scope='text'>{{ text | isActiveStatus }}</template>
                  <template slot='action' slot-scope='text, record, index'>
                    <a @click='handleDelete(record)'>删除</a>
                  </template>
                </a-table>
              </a-card>
            </a-col>
          </a-row>
        </a-spin>
      </a-tab-pane>
      <a-tab-pane key='2' tab='关联经销商'>
        <a-spin tip='Loading...' :spinning='false'>
          <a-row :gutter='10' style='padding: 10px; margin: -10px' v-if='visible'>
            <a-col :md='12' :sm='24'>
              <a-card :bordered='false'>
                <a-form layout='inline' @keyup.enter.native='searchQuery'>
                  <a-row :gutter='24'>
                    <a-col :md='7' :sm='24'>
                      <a-form-item label=''>
                        <a-input placeholder='职位编号' v-model='queryParam.positionCode'></a-input>
                      </a-form-item>
                    </a-col>
                    <a-col :md='7' :sm='24'>
                      <a-form-item label=''>
                        <a-input placeholder='职位名称' v-model='queryParam.positionName'></a-input>
                      </a-form-item>
                    </a-col>
                    <a-col :md='7' :sm='24'>
                      <a-button type='primary' @click='searchQuery' icon='search' style='margin-top: 5px'>查询</a-button>
                    </a-col>
                  </a-row>
                </a-form>
                <a-table
                  ref='table'
                  size='middle'
                  bordered
                  :scroll="{
                    x:'max-content'
                  }"
                  tableLayout='auto'
                  rowKey='positionCode'
                  :columns='positionsColumns'
                  :dataSource='positions'
                  :pagination='ipagination'
                  :loading='loading'
                  :rowSelection='{selectedRowKeys: positionSelectedRowKeys,
                   onSelect: onSelect,onSelectAll:onSelectAll}'
                  @change='handleTableChange'
                >

                  <template slot='mainPosition' slot-scope='text, record, index' v-if='false'>
                    {{ text }}
                  </template>
                  <template slot='imgUrl' slot-scope='text, record, index'>
                    <div class='anty-img-wrap'>
                      <a-avatar shape='square' :src='record.imgUrl' icon='user' />
                    </div>
                  </template>
                  <template slot='status' slot-scope='text'>{{ text | isActiveStatus }}</template>
                </a-table>

              </a-card>
            </a-col>
            <a-col :md='12' :sm='24'>
              <a-card :bordered='false'>
                <a-table
                  ref='table'
                  size='middle'
                  bordered
                  :scroll="{
                x:'max-content'
              }"
                  tableLayout='auto'
                  rowKey='positionCode'
                  :columns='positionsDataColumns'
                  :dataSource='positionsData'
                >

                  <template slot='mainPosition' slot-scope='text, record, index'>
                    <a-radio-group v-model='record.mainPosition' @change='onPositionChange(record,this)'>
                      <a-radio :value='0'>
                        主职
                      </a-radio>
                      <a-radio :value='1'>
                        副职
                      </a-radio>
                    </a-radio-group>
                  </template>
                  <template slot='imgUrl' slot-scope='text, record, index'>
                    <div class='anty-img-wrap'>
                      <a-avatar shape='square' :src='record.imgUrl' icon='user' />
                    </div>
                  </template>

                  <template slot='status' slot-scope='text'>{{ text | isActiveStatus }}</template>

                  <template slot='action' slot-scope='text, record, index'>
                    <a @click='handleDelete(record)'>删除</a>
                  </template>
                </a-table>
              </a-card>
            </a-col>
          </a-row>
        </a-spin>
      </a-tab-pane>
    </a-tabs>

  </j-modal>
</template>

<script>
import { filterObj } from '@/utils/util'
import { queryDepartTreeList, getUserList, queryUserByDepId } from '@/api/api'
import { getAction, postAction } from '@/api/manage'
import JInput from '@/components/cn-form/JInput.vue'
import { getStore } from '@/utils/storage'
import { PageListMixin } from '@/mixins/PageListMixin'

export default {
  name: 'config-modal',
  components: { JInput },
  props: {
    state:{
      type: Boolean,
      default:true,
    },
    modalWidth: {
      default() {
        return '1200px'
      }
    },
    'multi': Boolean
  },
  data() {
    return {
      typeLoading: false,
      queryParam: {
        code: '',
        name: ''
      },
      positions: [],
      positionsData: [],
      positionsColumns: [
        {
          title: '#',
          key: 'rowIndex',
          width: 60,
          align: 'center',
          customRender: function(t, r, index) {
            return parseInt(index) + 1
          }
        },
        {
          title: '职位编号',
          align: 'center',
          dataIndex: 'positionCode'
        },
        {
          title: '职位名称',
          align: 'center',
          dataIndex: 'positionName'
        },
        {
          title: '职位级别',
          align: 'center',
          dataIndex: 'positionLevel_dictText'
        }
      ],
      positionsDataColumns: [
        {
          title: '#',
          key: 'rowIndex',
          width: 60,
          align: 'center',
          customRender: function(t, r, index) {
            return parseInt(index) + 1
          }
        },
        {
          title: '职位编号',
          align: 'center',
          dataIndex: 'positionCode'
        },
        {
          title: '职位名称',
          align: 'center',
          dataIndex: 'positionName'
        },
        {
          title: '职位级别',
          align: 'center',
          dataIndex: 'positionLevel_dictText'
        },
        {
          title: '职位类型',
          align: 'center',
          dataIndex: 'mainPosition',
          scopedSlots: { customRender: 'mainPosition' }
        },
        {
          title: '操作',
          align: 'center',
          dataIndex: 'action',
          width: 80,
          ellipsis: true,
          scopedSlots: { customRender: 'action' }
        }
      ],
      customers: [],
      customersData: [],
      customersColumns: [
        {
          title: '#',
          key: 'rowIndex',
          width: 60,
          align: 'center',
          customRender: function(t, r, index) {
            return parseInt(index) + 1
          }
        },
        {
          title: '门店编号',
          dataIndex: 'customerCode'
        },
        {
          title: '门店名称',
          dataIndex: 'customerName'
        },
        {
          title: '操作',
          align: 'center',
          dataIndex: 'action',
          width: 80,
          ellipsis: true,
          scopedSlots: { customRender: 'action' }
        }
      ],
      roles: [],
      rolesData: [],
      scrollTrigger: {},
      customerSelectedRowKeys: [],
      customersSelectionRows: [],
      roleSelectedRowKeys: [],
      positionSelectedRowKeys: [],
      roleSelectionRows: [],
      positionSelectionRows: [],
      title: '用户配置',
      selectedKeys: [],
      visible: false,
      form: this.$form.createForm(this),
      loading: false,
      expandedKeys: [],
      userInfo: this.$store.getters.userInfo,
      activeKey: 'role',
      url: {
        list: '/cnProductController/getProductListByCust',
        selected: '/cnTerminalController/getCnTerminalByIdOrTerminalCode'
      },
      record: null

    }
  },
  mixins: [PageListMixin],
  computed: {
    // 计算属性的 getter
    getType: function() {
      return this.multi == true ? 'checkbox' : 'radio'
    }
  },
  watch: {
    visible(v) {
      if (v) {
        this.getSelectdData().then(() => {
          if (this.activeKey == 'org') {
            this.queryDepartTree()
          } else {
            this.loadData()
          }
        })
      }
    },
    activeKey() {
      if (this.activeKey == 'org') {
        this.queryDepartTree()
      } else {
        this.loadData()
      }
    }
  },
  created() {
    // 该方法触发屏幕自适应
    this.resetScreenSize()
  },
  methods: {
    onPositionChange(record) {
      let data = this[this.activeKey + 'sData']
      if (record.mainPosition == 0) {
        for (let i = 0; i < data.length; i++) {
          if (data[i].positionCode != record.positionCode) {
            data[i].mainPosition = 1
          }
        }
      }
    },
    /**
     * 删除已选中商品
     * @param record
     */
    handleDelete(record) {
      this[this.activeKey + 'sData'].removeByCode(record, this.activeKey + 'Code')
      this[this.activeKey + 'SelectionRows'].removeByCode(record, this.activeKey + 'Code')
      this[this.activeKey + 'SelectedRowKeys'].remove(record[this.activeKey + 'Code'])
    },
    /**
     * 标签页的选中事件
     * @param name
     */
    tabClick(name) {
      this.activeKey = name
    },
    /**
     * 递归树结构数据，取出所有子元素
     * @param children
     * @param selected
     * @returns {*}
     */
    getAllChildren(children, selected) {
      if (children && children.length) {
        children.map(child => {
          selected.push(child)
          this.getAllChildren(child.children, selected)
        })
      }
      return selected
    },
    /**
     * 选中树节点操作
     * @param checkedKeys
     * @param checked 不等于undefined 表示当前事件为checkbox事件，否则为点击树节点事件
     * @param checkedNodes
     * @param node
     * @param event
     */
    handleCheckbox(checkedKeys, { checked, checkedNodes, node, event }) {
      if (checked !== undefined) {
        //todo 当事件为checkbox事件时，checkedKeys当前选中的数据包含自节点数据
        this.selectedKeys = checkedKeys
        this.categoryData = this.getAllChildren(this.treeData, []).filter(node => checkedKeys.includes(node.code)).map(node =>
          Object.assign({}, node, {
            children: null
          }))
      } else {
        //todo 当事件为nodeClick事件时，checkedKeys当前选中数据为当前点击节点
        const checkNodes = [node.dataRef, ...this.getAllChildren(node.dataRef.children, [])]
        //todo 如果当前点击节点已经被选中，则执行删除操作
        if (this.selectedKeys.includes(node.dataRef.code)) {
          checkNodes.map(node => {
            this.selectedKeys.remove(node.code)
            //todo 从右边table删除选中数据
            this.categoryData.remove(node)
          })
        } else {
          this.selectedKeys = Array.from(new Set(this.selectedKeys.concat(checkNodes.map(node => node.code))))
          //todo 添加选中数据到右边table
          this.categoryData = Array.from(new Set([...this.categoryData, ...checkNodes.map(node => Object.assign({}, node, {
            children: null
          }))]))
        }

      }
    },
    // 触发屏幕自适应
    resetScreenSize() {
      let screenWidth = document.body.clientWidth
      if (screenWidth < 500) {
        this.scrollTrigger = { x: 800 }
      } else {
        this.scrollTrigger = {}
      }
    },
    showModal(record) {
      this.userInfo = record
      this.visible = true
      this.form.resetFields()
    },
    /**
     * 获取查询参数
     * @returns {*}
     */
    getQueryParams() {
      let param = Object.assign({}, this.queryParam)
      param.current = this.ipagination.current
      param.size = this.ipagination.pageSize
      return filterObj(param)
    },
    searchReset(num) {
      let that = this
      if (num !== 0) {
        that.loadData(1)
      }
      that[this.activeKey + 'SelectedRowKeys'] = []
      that[this.activeKey + 'SelectionRows'] = []
      that.selectedKeys = []
      that[this.activeKey + 'sData'] = []
      that.categoryData = []
    },
    close() {
      this.searchReset(0)
      this.visible = false
    },
    handleSubmit() {
      let that = this
      that.$emit('ok', {
        positions: that['positionsData'],
        roles: that['rolesData'],
        customers: that['customersData'],
        username: this.userInfo.userName
      })
      that.searchReset(0)
      that.close()
    },
    /**
     * 手动全选/取消全选分类
     * @param selected
     * @param selectedRows
     * @param changeRows
     */
    onSelectAll(selected, selectedRows, changeRows) {
      this[this.activeKey + 'SelectedRowKeys'] = selectedRows.map(row => row[this.activeKey + 'Code'])
      this[this.activeKey + 'SelectionRows'] = selectedRows
      if (selected) {
        let data_ = this[this.activeKey + 'sData']
        //todo 选中
        changeRows.map(row => {
          let n = 0
          if (data_ != null && data_ != undefined) {
            // debugger
            for (let i = 0; i < data_.length; i++) {
              if (data_[i].mainPosition == 0) {
                n = 1
                break
              }
            }
            if (n == 1) {
              row.mainPosition = 1
            }
          }
          this[this.activeKey + 'sData'].push(row)
        })
      } else {
        //todo 取消选中
        changeRows.map(row => {
          this[this.activeKey + 'sData'].removeByCode(row, this.activeKey + 'Code')
        })
      }
    },

    /**
     * 手动勾选/取消分类
     * @param record
     * @param selected
     * @param selectedRows
     * @param nativeEvent
     */
    onSelect(record, selected, selectedRows, nativeEvent) {
      this[this.activeKey + 'SelectedRowKeys'] = selectedRows.map(row => row[this.activeKey + 'Code'])
      this[this.activeKey + 'SelectionRows'] = selectedRows.slice(0)
      if (selected) {
        //todo 选中
        let data_ = this[this.activeKey + 'sData']
        let n = 0
        if (data_ != null && data_ != undefined) {
          // debugger
          for (let i = 0; i < data_.length; i++) {
            if (data_[i].mainPosition == 0) {
              n = 1
              break
            }
          }
          if (n == 1) {
            record.mainPosition = 1
          }
        }
        this[this.activeKey + 'sData'].push({ ...record })
      } else {
        //todo 取消选中
        this[this.activeKey + 'sData'].removeByCode(record, this.activeKey + 'Code')
      }


    },
    onSearch() {
      this.loadData(1)
    },

    /**
     * 覆盖mixin的loadData方法
     * @param arg
     * @returns {Promise<void>}
     */
    async loadData(arg) {
      let params = this.getQueryParams()//查询条件
      if (arg === 1) {
        this.ipagination.current = 1
      }
      let url
      if (this.activeKey === 'position') {
        url = '/cnPositionController/getNoPosPageList'
      }
      if (this.activeKey === 'role') {
        url = '/cnRoleController/getRoleList'
      }
      if (this.activeKey === 'customer') {
        url = '/customer/cnCustomer/findPageList'
        params.permflag = 'purchase_customer_page_impl_add_cust'
        params.userType = 1
      }
      this.loading = true
      await postAction(url, { ...params }).then((res) => {
        if (res.success) {
          this[this.activeKey + 's'] =
            this.activeKey === 'position' ? res.result.records.map(row => Object.assign({}, row, {
              mainPosition: 0
            })) : res.result.records
          this.ipagination.total = res.result.total
        }
      }).finally(() => {
        this.loading = false
      })
    },
    /**
     * 获取已选中数据
     */
    getSelectdData() {

      const positionUrl = '/cnPositionController/getListByUsername'
      const roleUrl = '/cnRoleController/getRoleListByUsername'
      const customerUrl = '/customer/cnCustomer/getCantactPage'
      return Promise.all([
        getAction(roleUrl, { userName: this.userInfo.userName }),
        getAction(positionUrl, { username: this.userInfo.userName }),
        getAction(customerUrl, { username: this.userInfo.userName })
      ]).then(([roles, positions, customers]) => {
        if (roles.result && roles.result.length) {
          this['roleSelectedRowKeys'] = roles.result.map(row => row.roleCode)
          this['roleSelectionRows'] = roles.result
          this['rolesData'] = roles.result
        }
        if (positions.success && positions.result && positions.result.length) {
          this['positionSelectedRowKeys'] = positions.result.map(row => row.positionCode)
          this['positionSelectionRows'] = positions.result
          this['positionsData'] = positions.result
        }
        if (customers.success && customers.result && customers.result.length) {
          this['customerSelectedRowKeys'] = positions.result.map(row => row.customerCode)
          this['customersSelectionRows'] = positions.result
          this['customersData'] = positions.result
        }
      })
    },
    /**
     * 获取分类树
     * @returns {*}
     */
    queryDepartTree() {
      this.typeLoading = true
      return queryDepartTreeList().then((res) => {
        if (res.success) {
          this.treeData = this.handleStruct(res.result)
          // 默认展开父节点
          this.expandedKeys = this.treeData.map(item => item.code)
        }

        this.typeLoading = false
      }).catch(e => {
        this.$message.warning(res.message)
        this.typeLoading = false
      })
    },
    /**
     * 重构树结构数据
     * @param tree
     * @returns {*}
     */
    handleStruct(tree) {
      return tree.map(t => {
        const json = Object.assign({}, t, {
          code: t.orgCode,
          name: t.orgName,
          type: t.orgType
        })
        if (json.children) {
          json.children = this.handleStruct(json.children)
        }
        return json
      })
    },
    modalFormOk() {
      this.loadData()
    }
  }
}
</script>

<style scoped>
.ant-table-tbody .ant-table-row td {
  padding-top: 10px;
  padding-bottom: 10px;
}

#components-layout-demo-custom-trigger .trigger {
  font-size: 18px;
  line-height: 64px;
  padding: 0 24px;
  cursor: pointer;
  transition: color .3s;
}
</style>
